//console.show();
const api = require("./api.js")
const Gaode = require("./gaode.js")

function requestPermission(permission) {
    try {
        var activity = context
        var pm = activity.getPackageManager()
        var packageName = activity.getPackageName()
        
        // 检查是否已有权限
        if (pm.checkPermission(permission, packageName) === android.content.pm.PackageManager.PERMISSION_GRANTED) {
            log("已有权限: " + permission)
            return true
        } else {
            log("需要权限: " + permission)
            // 在AutoXjs中，通常权限已经在manifest中声明，可以直接使用
            return false
        }
    } catch (e) {
        log("权限检查错误: " + e)
        return false;
    }
}

function getCurrentGPS() {
    // 检查位置权限
    requestPermission("android.permission.ACCESS_FINE_LOCATION")

    requestPermission("android.permission.ACCESS_COARSE_LOCATION")


    // 获取系统定位服务
    var locationManager = context.getSystemService(context.LOCATION_SERVICE)

    // 尝试从GPS获取最后一次已知位置
    var gpsLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER)
    // 如果GPS没有，尝试从网络获取
    if (gpsLocation == null) {
        gpsLocation = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER)
    }

    if (gpsLocation == null) {
        log("无法获取最后一次已知位置")
        return false
    }

    
    var latitude = gpsLocation.getLatitude()
    var longitude = gpsLocation.getLongitude()
    let gaode = new Gaode()
    let gps = gaode.wgs84ToGcj02(longitude, latitude) //{longitude, latitude}
    log("经度: " + gps.longitude + ", 纬度: " + gps.latitude)
    return gps
}


module.exports = {
  getCurrentGPS: getCurrentGPS
}